<template>
    <div>
        <!-- 按钮区 -->
        <div>
            <el-button type="primary" size="big" style="width:90px ;" class="el-icon-plus"
                v-if="$hasBP('btn.Trademark.add')" @click="addTrademark">添加
            </el-button>
        </div>
        <!-- 表单区 -->
        <div>
            <el-table :data="trademarks" border style="width: 100%" v-loading="loading">
                <el-table-column type="index" label="序号" width="180">
                </el-table-column>
                <el-table-column prop="tmName" label="角色名称" width="180">
                </el-table-column>
                <el-table-column prop="tradename" label="品牌logo" width="180">
                    <template slot-scope="scope">
                        <a :title="scope.row.tmName">
                            <img :src="scope.row.logoUrl" alt=""
                                style="width: 100px; height: 60px; border-radius: 10px" />
                        </a>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button class="el-icon-edit" type="warning" title="修改商品" @click="updateTrademark(scope)">修改
                        </el-button>
                        <el-button class="el-icon-delete" type="danger" title="删除商品" @click="deleteTrademark(scope)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页区 -->
        <div>
            <!-- 使用了size-change和current-change事件来处理页码大小和当前页变动时候触发的事件。 -->
            <el-pagination @size-change="handleSizeChange" @current-change="getTradeList" :current-page="page"
                :page-size="limit" :page-sizes="[3,5,7]" layout="prev, pager, next, jumper,->,sizes,total"
                :total="this.total">
            </el-pagination>
        </div>

        <!-- 对话框区 -->
        <el-dialog :title="form.id?'修改品牌':'添加品牌'" :visible.sync="dialogFormVisible">
            <el-form :model="form" ref="form" :rules="rules">
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="form.tmName" style="width: 400px;"></el-input>
                </el-form-item>
                <el-form-item label="品牌Logo" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload"
                        :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="getAdd">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getTrademarkList, getAddTrademarkList, getDeleteTrademark } from '@/api/product/trademark'
export default {
    data() {
        return {
            trademarks: [],
            total: 20, //  总条数
            page: 1, // 当前页码
            limit: 3, // 分页器选择的展示几条数据，默认是3(一页展示几条)

            //  点击添加弹出的对话框
            dialogFormVisible: false,
            form: {
                tmName: '',
                logoUrl: '',
            },
            loading: false,
            //    图片容器
            imageUrl: '',
            // 表单验证规则
            rules: {
                tmName: [
                    { required: true, message: '请输入品牌名称', trigger: 'blur' },
                    { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
                ],
                logoUrl: [{
                    required: true,
                    message: 'LOGO必须指定',
                }],
            }
        }
    },
    mounted() {
        this.getTradeList()
    },
    methods: {
        // 获取品牌列表数据
        async getTradeList(page) {
            this.loading = true
            //   更新当前页码
            this.page = page
            let result = await getTrademarkList(page, this.limit)
            this.loading = false
            // console.log(result);
            // 如果成功了, 更新数据显示
            const { records, total } = result.data
            this.trademarks = result.data.records
            this.total = result.data.total
            // this.limit = result.pages
        },
        // 当修改每页数量的监听回调
        handleSizeChange(pageSize) {
            // pageSize就是选择的每页展示几条数据
            // console.log(pageSize);
            // 更新limit/
            this.limit = pageSize
            console.log(this.limit);
            // 重新获取第一页数据显示
            this.getTradeList()
        },
        //   点击添加展示对话框
        addTrademark() {
            this.dialogFormVisible = true,
                // 点击添加弹出对话框应该把上次的内容信息清空

                this.form.tmName = '',
                this.form.logoUrl = '',
                // 数据变化必然导致界面变化
                // 但界面是数据改变后异步更新的 ===> 此时界面还没有变化(就是没有显示)

                // 在显示了提示信息后, 立即清除提示信息
                // 此时dialog界面还没有显示 ==> 必须延迟到界面更新显示后再执行
                this.$nextTick(() => {
                    this.$refs.form.resetFields()
                })

        },
        // 点击修改展示对话框
        updateTrademark(scope) {
            this.dialogFormVisible = true,
                this.form.tmName = scope.row.tmName
            this.form.logoUrl = scope.row.logoUrl
            this.form.id = scope.row.id
            this.$nextTick(() => {
                this.$refs.form.clearValidate()
            })
        },
        // 点击dialog确定按钮的回调
        getAdd() {
            //   验证表单规则
            // 对所有表单项进行统一校验
            this.$refs['form'].validate(async (valid) => {
                // 校验完成的回调
                // 如果通过, 才进行后面请求的操作
                // valid是boolean值
                // console.log(valid);
                // 如果通过, 才进行后面的回调
                if (valid) {
                    let result = await getAddTrademarkList(this.form)
                    if (result.code == 200) {
                        this.$message({
                            type: 'success',
                            message: (this.form.id ? "修改品牌成功" : "添加品牌成功")
                        })
                        //  修改成功之后再次获取最新的列表数据
                        this.getTradeList(this.page)
                    }
                } else {
                    alert('验证失败')
                    return
                }
                this.dialogFormVisible = false
            })
        },
        //    点击删除品牌图片按钮
        async deleteTrademark(scope) {
            try {
                //删除品牌成功
                await getDeleteTrademark(scope.row.id)
                //提示信息
                this.$message({
                    type: "success",
                    message: `删除${scope.row.tmName}成功`,
                });
                //再次获取最新数据
                this.getTradeList();
            } catch (error) { }
        },
        //    对话框上传回调成功
        handleAvatarSuccess(res, file) {
            this.form.logoUrl = URL.createObjectURL(file.raw);
        },
        // 对话框上传回调之前
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }

    },


}
</script>

<style>
/* 对话框上传样式 */
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>